<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form class="antd-modal-form" v-bind="formItemLayout" ref="formRef">
          <a-row>
            <a-col :span="24">
              <a-form-item label="包材" v-bind="validateInfos.packagingId" v-auth="'packaging:purchase'">
                <j-search-select :disabled="true" v-model:value="formData.packagingId" dict="p_packaging_details,name,id"  allow-clear />
              </a-form-item>
              <a-form-item label="包材" v-bind="validateInfos.packagingId" v-auth="'packaging:factory'">
                <j-search-select :disabled="true" v-model:value="formData.packagingId"  :dict="`p_packaging_details where factory_id='${userInfo.factoryId}',name,id`"  allow-clear />
              </a-form-item>

            </a-col>
						<a-col :span="24">
							<a-form-item label="到货数量" v-bind="validateInfos.num">
								<a-input-number v-model:value="formData.num" placeholder="请输入到货数量"  :precision="2" :addon-after="unit" allow-clear ></a-input-number>
							</a-form-item>
						</a-col>

          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import {ref, reactive, defineExpose, nextTick, onMounted, inject, defineProps, unref, watch} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { getValueType } from '/@/utils';
  import { packagingOrderDetailsSaveOrUpdate } from '../PackagingOrder.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import {initDictOptions} from "@/utils/dict";
import {useUserStore} from "@/store/modules/user";

  //接收主表id
  const mainId = inject('mainId');
  const packagingId = inject('packagingId');
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
        id: '',
        num: '',   
        packagingId: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const unit = ref();
  //表单验证
  const validatorRules = {
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const props = defineProps({
    disabled: { type: Boolean, default: false },
  });
  const formItemLayout = {
    labelCol: { xs: { span: 24 }, sm: { span: 5 } },
    wrapperCol: { xs: { span: 24 }, sm: { span: 16 } },
  };
const userStore = useUserStore();
const userInfo = userStore.getUserInfo;

  watch(() => formData.packagingId, (newValue) => {
    // formData.specCode.value = null
    // console.log(specCodeDict.value)
    // console.log(addDisabled.value)
    // if (!addDisabled.value) {
    //   formData.specNo = null
    // }
    // specCodeDict.value = `goods_info_spec where goods_no = "${newGoodsNo}",spec_no,spec_no`;
    if (newValue) {
      const dictData = initDictOptions('p_packaging_details,unit,unit,'+ encodeURIComponent(`id = '${newValue}'`))
      dictData.then(res=>{
        console.log(res[0])
        if (res[0]) {
          unit.value = res[0].value
        }else {
          unit.value = ''
        }

      })
    }

  });
  
  /**
   * 新增
   */
  function add() {
    console.log( unref(packagingId))
    edit({"packagingId":unref(packagingId)});
    formData.packagingId = unref(packagingId)
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData,tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    if (unref(unit)) {
      model['unit'] = unref(unit);
    }
   
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    if (unref(mainId)) {
      model['packagingOrderId'] = unref(mainId);
    }
    await packagingOrderDetailsSaveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
